#!/bin/bash
#mkdir -p ~/$NGINX1/www ~/$NGINX1/logs ~/$NGINX1/conf

nginxs=(
"nginx1"
"nginx2"
)

#FROM xujian:keepalived
gen_nginx_docker_file()
{
    cat <<-EOF >$1"_docker_file"
FROM yidian:ubuntu1
RUN mkdir -p /opt/logs
RUN mkdir -p /www
ADD docker_init.sh /opt/
ADD web1.py /opt/web.py
ADD check_nginx.sh /etc/keepalived/
ADD www.yidian.com.crt /opt/
ADD www.yidian.com.key /opt/
ADD s-nail.rc /opt/
ADD mail_notify.sh /etc/keepalived/
ADD muttrc /opt/
ADD msmtprc /opt/
ADD $1/keepalived/keepalived.conf /etc/keepalived/
ADD $1/conf/nginx.conf /etc/nginx/nginx.conf
ADD $1/www/index.html /www
CMD ["/bin/bash","-c","/opt/docker_init.sh"]
EOF
}

#clean old nginxs
for container in "${nginxs[@]}"
do
    docker rm -f $container >/dev/null 2>&1
    docker rmi -f $container >/dev/null 2>&1
done

addhosts=' '
addhosts=${addhosts}"--add-host="webserver1":"172.19.0.11" "
addhosts=${addhosts}"--add-host="webserver2":"172.19.0.12" "
addhosts=${addhosts}"--add-host="webserver3":"172.19.0.13" "
addhosts=${addhosts}"--add-host="webserver4":"172.19.0.14" "

#create network
ipstart="172.19.0."
docker network rm newnetwork
docker network create --subnet=$ipstart'0/24' newnetwork

i=11
for container in "${nginxs[@]}"
do
    gen_nginx_docker_file $container
    docker build -f $container"_docker_file" -t $container .
    #docker run  --name $container --network newnetwork --ip $ipstart$i -v $PWD/$container/conf/nginx.conf:/etc/nginx/nginx.conf -v $PWD/$container/www:/www -d $container
    #docker run  --name $container --network newnetwork --cap-add=NET_ADMIN --ip $ipstart$i -d $container
    docker run  --name $container --network newnetwork --restart=always $addhosts --cap-add=NET_ADMIN --ip $ipstart$i -d $container
    let i=$i+1
    sleep 10
done
